package work;

import java.awt.Point;
import java.awt.Polygon;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;












import model.Grid;
import model.MyPoint;
import model.Site;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

import utils.UtilJdbc;
import dao.impl.GridDaoImpl;

/**  kml 中的 <kml xmlns="http://earth.google.com/kml/2.0"> 会影响xml文件的解析
 * @author nsl
 *
 */
public class ParseXml {
	
	private GridDaoImpl gridDao=new GridDaoImpl();
	
	@Test
	public void demo1(){
		SAXReader saxReader = new SAXReader();
		saxReader.setEncoding("gbk"); 
		System.out.println(new File("/").getAbsolutePath());
		
	    Document document=null;
	    //String fileAbString="d:/2area.kml";
	    String fileAbString="Z:/SynBaiDu/Work/网优小工具/转换指导书和插件/jy_jz.kml";
		try {
			document = saxReader.read(new File(fileAbString));
		} catch (DocumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String elementNameString="//Placemark";
		List rowList = document.selectNodes(elementNameString); 
		
		List<Grid> gridList=new ArrayList<>();
		
		for(Iterator iterator=rowList.iterator();iterator.hasNext();){
			
			Grid grid=new Grid();
			
			Element element=(Element) iterator.next();
			//System.out.println(element.getName());
			
			Element elementName=element.element("name");
			//System.out.println(elementName.getTextTrim());
			grid.setGridName(elementName.getTextTrim());

			//Element elementPoints=element.element("coordinates");
			
			Node elementPoints=element.selectSingleNode("//coordinates");
			//System.out.println(elementPoints.getText());
			String coordinatesString=elementPoints.getText();
			String[] xyzArray=coordinatesString.split("\n");
			for(int i=0;i<xyzArray.length;i++){
				String xyz=xyzArray[i];
				if(xyz.trim().equals("")){
					continue;
				}
				String[] points=xyz.split(",");
				//System.out.println(points[0]+"  "+points[1]);
				double x=Double.parseDouble(points[0].trim());
				double y=Double.parseDouble(points[1].trim());
				MyPoint point=new MyPoint(x,y);
				
				grid.getPointList().add(point);
			}
			gridList.add(grid);
		}
		System.out.println(gridList);
		for(Grid g:gridList){
			gridDao.add(g);
		}
		
		
	  /*  System.out.println(elementNameString+".size() = "+rowList.size());
		// 获取根元素
	    Element root = document.getRootElement();
	    System.out.println("Root: " + root.getName());
		List<Element> childrenList=root.elements();
	    System.out.println(childrenList.size());
	    Element element=childrenList.get(0);
	    System.out.println(element.getName());
	    System.out.println(element.elements().size());*/
	    
	    
	    
	}

	@Test
	public void demo2(){
		Grid grid=new Grid();
		grid.setGridName("test");
		grid.getPointList().add(new MyPoint(1d,2d));
		gridDao.add(grid);
		
	}

	@Test
	public void demo3(){
		List<Grid> list=gridDao.getAll();
		System.out.println(list);
		
	}
	
	@Test
	public void readCsv(){
		List<Grid> list=gridDao.getAll();
		List<Site> siteList=new ArrayList<Site>();
		
		long rowNumber=0;
		 try {      
             ArrayList<String[]> csvList = new ArrayList<String[]>(); //用来保存数据  
             String csvFilePath = "Z:/SynBaiDu/Work/2016年省公司工作/网格图层/4G_NodeB_Jy.csv";  
              CsvReader reader = new CsvReader(csvFilePath,',',Charset.forName("gbk"));    //一般用这编码读就可以了      
                
              reader.readHeaders(); // 跳过表头   如果需要表头的话，不要写这句。  
                
              while(reader.readRecord()){ //逐行读入除表头的数据      
                  csvList.add(reader.getValues());  
              }              
              reader.close();  
              System.out.println(csvList.size());
              String outFile = "d:/test.csv";  
              CsvWriter wr =new CsvWriter(outFile);
              String[] head={"城市","基站编号","经度","纬度","网格编号"};
              wr.writeRecord(head);
              for(int row=0;row<csvList.size();row++){
            	  rowNumber=row+1;
                  System.out.println(row);
                  String[] array=csvList.get(row);
                  String  siteName = csvList.get(row)[0];
                  double longitude=Double.parseDouble(array[2]);
                  double latitude=Double.parseDouble(array[3]);
                  Site site=new Site(array[0],array[1],longitude,latitude);
                  siteList.add(site);
                  List<String> outRow=new ArrayList<>();
                  outRow.containsAll(Arrays.asList(array));
                  for(Grid g:list){
                	  if(isContainPoint(g,new MyPoint(longitude, latitude))){
                		  outRow.add(g.getGridName());
                		  System.out.println("write output : "+g.getGridName());
                		  wr.writeRecord((String[]) outRow.toArray());
                	  }
                  }
                  
                
                  //取得第row行第0列的数据 
                  /*if(!siteName.equals("")){
                	  System.out.println("cell="+siteName);  
                  }
                  System.out.println("cell="+siteName);  */
              }  
              wr.close(); 
              System.out.println(siteList.size());
         }catch(Exception ex){  
        	 System.out.println("row["+rowNumber+"] is error.");
             System.out.println(ex);  
         }  
		 List<Grid> gridList=gridDao.getAll();
	}
	
	public boolean isContainPoint(Grid grid,MyPoint point){
		int times=100000;
		List<MyPoint> points=grid.getPointList();
		Polygon polygon=new Polygon();
		for(MyPoint p:points){
			int x=(int) Math.floor(p.getX()*times);
			int y=(int) Math.floor(p.getY()*times);
			//System.out.println("x= "+x);
			polygon.addPoint(x, y);
		}
		boolean result=polygon.contains(point.getX()*times, point.getY()*times);
		return result;
	}
	
	@Test
	public void testContain(){
		Grid grid=new Grid();
		grid.setGridName("aa");
		grid.getPointList().add(new MyPoint(0, 0));
		grid.getPointList().add(new MyPoint(0, 2));
		grid.getPointList().add(new MyPoint(2, 2));
		grid.getPointList().add(new MyPoint(2, 0));
		MyPoint point=new MyPoint(1,1);
		boolean flag=isContainPoint(grid, point);
		System.out.println(flag);
		
		List<Grid> list=gridDao.getAll();
		Grid g=list.get(0);
		System.out.println(g);
		flag=isContainPoint(g, point);
		System.out.println(flag);
	}
}
